<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <todo-header @create="createFn" :arr="list"></todo-header>
    <todo-main :arr="showAll" @del="deleteFn"></todo-main>
    <todo-footer
      :farr="showAll"
      @clear="clearFun"
      @chageType="typeFn"
    ></todo-footer>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

// 组件引入
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  data() {
    return {
      //从本地取数据 如果本地有数据从本地取 本地没有返回一个空数组
      list: JSON.parse(localStorage.getItem("todoList")) || [],
      // 显示全部
      getSel: "all",
    };
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  methods: {
    createFn(taskName) {
      // 有数据 使最大数据加1
      let id =
        this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1;
      if (taskName === "") {
        return alert("任务名不能为空");
      }
      this.list.push({
        id: id,
        name: taskName,
        isDone: false,
      });
    },
    deleteFn(thenId) {
      const index = this.list.findIndex((item) => {
        return item.id === thenId;
      });
      // 找到对应的索引号
      // console.log(index);
      // 通过索引号删除 1行
      this.list.splice(index, 1);
    },
    typeFn(str) {
      this.getSel = str;
    },
    clearFun() {
      // 筛选为obj.isDone为false的数据
      this.list = this.list.filter((obj) => obj.isDone == false);
      console.log(this.list);
    },
  },
  computed: {
    showAll() {
      if (this.getSel === "yes") {
        return this.list.filter((obj) => obj.isDone === true);
      } else if (this.getSel === "no") {
        return this.list.filter((obj) => obj.isDone === false);
      } else {
        return this.list;
      }
    },
  },
  // 监听事件
  watch: {
    // 监听list
    list: {
      //深度监听
      deep: true,
      handler() {
        // 数据发生变化 存到本地 转为JSON字符串存
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>
   